<template>
  <TableWrap @refresh="getDeptListByRole">
    <template #headerLeft>
      <a-space>
        <a-cascader v-model="searchName" :options="deptAll" style="width: 300px" @change="getDeptListByRole" :field-names="{ value: 'deptName', label: 'deptName' }" placeholder="部门查询" check-strictly allow-clear allow-search />

        <!-- <a-input-search style="width: 260px" v-model="searchName" @change="getDeptListByRole" /> -->
        <a-button type="primary" size="medium" @click="showChooseDeptDialog = true">添加部门</a-button>
        <a-button class="gray-outline" @click="removeDept(selectRow)">批量移除</a-button>
      </a-space>
    </template>
    <template #tableBody>
      <a-table
        class="table-singe-line show-border-table"
        :scroll="{
          y: '100%',
        }"
        ref="tableRef"
        :loading="tableLoading"
        @selection-change="selectColumn"
        :row-selection="rowSelection"
        row-key="id"
        :columns="tableColumns"
        :data="deptList"
        size="mini"
        :pagination="false"
      >
        <template #columns>
          <a-table-column v-for="(item, index) of tableColumns" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
            <template v-if="item.title === '操作'" #cell="{ record }">
              <a-space>
                <a-button type="text" size="mini" @click="removeDept([record.id])">移除</a-button>
              </a-space>
            </template>
            <template v-else #cell="{ record }">
              {{ record[item.dataIndex] }}
            </template>
          </a-table-column>
        </template>
      </a-table>
    </template>
  </TableWrap>
  <!-- 授权部门-->
  <a-modal :width="500" v-model:visible="showChooseDeptDialog" title="授权部门" title-align="start" ok-text="确认添加" :mask-closable="false" @cancel="checkedDept = []" :on-before-ok="addDept" :ok-loading="addLoading">
    <div style="min-height: 150px">
      <div class="flex">
        <p style="margin-right: 10px">部门</p>
        <a-cascader v-model="checkedDept" :options="deptAll" :max-tag-count="10" style="width: 300px" :field-names="{ value: 'id', label: 'deptName' }" placeholder="" multiple check-strictly />
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { getOrganizes } from '@/api/system'
  import { roleBindDept, getDeptByRole, roleUnbindDept } from '@/api/system'
  import { Message, Modal } from '@arco-design/web-vue'
  const props = defineProps({
    roleId: {
      type: String,
    },
  })
  const tableLoading = ref(false)
  const deptList = ref<Array<any>>([])
  const deptAll = ref<Array<any>>([])
  const selectRow = ref([]) //选中数据
  const addLoading = ref(false)
  const searchName = ref()
  const checkedDept = ref()
  const tableRef = ref()
  const showChooseDeptDialog = ref(false)
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const tableColumns: Array<any> = [
    {
      title: '部门',
      dataIndex: 'fullDeptName',
    },
    {
      title: '授权总人数',
      dataIndex: 'deptUserNum',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 80,
    },
  ]
  // 获取部门列表
  async function getDeptsList() {
    const res: any = await getOrganizes()
    deptAll.value = res?.data || []
  }
  getDeptsList()
  // 获取当前角色下的部门列表
  async function getDeptListByRole() {
    tableLoading.value = true
    const res: any = await getDeptByRole({
      roleId: props.roleId,
      pageNum: 1,
      pageSize: 1000,
      deptName: searchName.value,
    })
    tableRef.value.selectAll(false)

    tableLoading.value = false
    deptList.value = res?.data?.records || []
    deptList.value.forEach((el: any) => {
      delete el.children
    })
  }
  getDeptListByRole()

  // 选中数据
  function selectColumn(val: any) {
    selectRow.value = val
  }
  // 添加部门
  async function addDept() {
    if (!checkedDept.value?.length) {
      Message.error('请选择部门')
      return false
    }
    addLoading.value = true
    const res: any = await roleBindDept({
      id: props.roleId,
      deptIds: checkedDept.value,
    })
    addLoading.value = false
    if (!res) return false
    Message.success('添加成功')
    getDeptListByRole()
    return true
  }
  // 移除部门
  function removeDept(ids: any) {
    if (!ids?.length) {
      return Message.error('请选择需要操作的数据')
    }
    Modal.error({
      title: '移除确认',
      content: '请再次确认，把选中部门从该权限中移除？',
      titleAlign: 'start',
      hideCancel: false,
      onOk: async () => {
        const res: any = await roleUnbindDept({
          id: props.roleId,
          deptIds: ids,
        })
        if (res) {
          Message.success('移除成功')
          getDeptListByRole()
        }
      },
    })
  }
  defineExpose({ getDeptListByRole })
</script>

<style lang="less" scoped></style>
